package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XuechengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.model.dto.*;
import com.xuecheng.content.model.enums.AuditStatusEnum;
import com.xuecheng.content.model.enums.PublishStatus;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDTO queryCourseParamsDTO) {
        //构建查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();

        //课程名称是模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDTO.getCourseName()),CourseBase::getName,queryCourseParamsDTO.getCourseName());
        //审核状态是等值查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDTO.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDTO.getAuditStatus());
        //发布状态是等值查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDTO.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDTO.getPublishStatus());

        //构建分页参数
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());

        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);

        //封装数据
        List<CourseBase> records = pageResult.getRecords();
        long total = pageResult.getTotal();
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(records,total,pageParams.getPageNo(),pageParams.getPageSize());
        return courseBasePageResult;
    }

    @Override
    @Transactional
    public CourseBaseInfoDto addCourseBase(AddCourseDto addCourseDto) {
        //分两个表进行插入，分别是课程信息表和课程影响表，然后封装CourseBaseInfoDto数据对前端进行返回
        //判断数据合法性
        if(addCourseDto == null){
            XuechengPlusException.cast(CommonError.Request_Null);
        }
        if(StringUtils.isBlank(addCourseDto.getName())){
            XuechengPlusException.cast("课程名称为空");
        }

        //1. 先插入课程信息表，才能获得到他的课程id
        CourseBase courseBase = new CourseBase();
        //这里我们不能获取到公司id，因为前端没有传递过来，我们这里写死 TODO 后续需要进行网关，用户登录通过线程池获取
        courseBase.setCompanyId(1L);
        BeanUtils.copyProperties(addCourseDto,courseBase);
        //补充字段
        courseBase.setAuditStatus(AuditStatusEnum.NOT_SUBMIT);
        courseBase.setStatus(PublishStatus.NOT_PUBLISH);
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setChangeDate(LocalDateTime.now());
        courseBaseMapper.insert(courseBase);

        //2. 获取课程id，插入课程营销表
        Long courseId = courseBase.getId();
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseMarket);

        //再次我们检验数据的合法性，因为如果是免费课程，那么现价应该为0
        if("20100".equals(courseMarket.getCharge())){
            courseMarket.setPrice(0f);
        }
        courseMarket.setId(courseId);
        //先判断数据空中是否存在课程营销表，如果存在，那么就修改，不存在就插入
        if(courseMarketMapper.selectById(courseId) != null){
            courseMarketMapper.updateById(courseMarket);
        }
        courseMarketMapper.insert(courseMarket);

        //3.封装CourseBaseInfoDto数据对前端进行返回
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        //补充大小名称
        //大名称，应该向课程分类表中查询该id，然后获取到他的名称
        CourseCategory Mt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(Mt.getName());
        //小名称
        CourseCategory St = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(St.getName());

        return courseBaseInfoDto;
    }

    /**
     * 根据课程id查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId) {
        //需要结合两张表
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        //补充分类名称
        CourseCategory mt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(mt.getName());
        CourseCategory st = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(st.getName());


        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        return courseBaseInfoDto;
    }

    /**
     *  修改课程信息
     * @param editCourseDto
     * @return
     */
    @Override
    @Transactional
    public CourseBaseInfoDto updateCourseBase(EditCourseDto editCourseDto) {
        //先判断该课程在数据库中是否存在
        Long id = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(courseBase == null){
            XuechengPlusException.cast("课程不存在");
        }

        //检验本机构只能修改本机构的课程
        if(courseBase.getCompanyId() != 1232141425L){
            XuechengPlusException.cast("本机构只能修改本机构的课程");
        }
        BeanUtils.copyProperties(editCourseDto,courseBase);
        //更新对应的数据表
        courseBaseMapper.updateById(courseBase);

        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        if("20100".equals(courseMarket.getCharge())){
            courseMarket.setPrice(0f);
        }
        if(courseMarketMapper.selectById(id) != null){
            courseMarketMapper.updateById(courseMarket);
        }else{
            courseMarketMapper.insert(courseMarket);
        }

        //封装CourseBaseInfoDto
        return getCourseBaseInfo(id);
    }


}
